package cn.wolfcode.luowowo.redis.impl;

import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.redis.IUserRedisService;
import cn.wolfcode.luowowo.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserRedisServiceImpl implements IUserRedisService {
    @Autowired
    private StringRedisTemplate template;

    /**
     * 验证码保存
     * @param phone 手机号码
     * @param code 验证码
     */
    @Override
    public void setCode(String phone, String code) {
        String key = RedisKeys.VERIFY_CODE.join(phone);
        template.opsForValue().set(key,code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    }

    /**
     * 获取验证码
     * @param phone
     * @return
     */
    @Override
    public String getCode(String phone) {
        String key = RedisKeys.VERIFY_CODE.join(phone);
        String code = template.opsForValue().get(key);
        return code;
    }

    /**
     * 保存登录令牌
     * @param token
     * @param userInfo
     */
    @Override
    public void setToken(String token, UserInfo userInfo) {
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        String user = JSON.toJSONString(userInfo);
        template.opsForValue().set(key,user, RedisKeys.USER_LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
    }

    /**
     * 限制同一个手机号在一天之内发送3次短信
     * @param phone
     */
    @Override
    public void sendCodeTimes(String phone) {
        String key = "send_code_times"+phone;
        String value = template.opsForValue().get(key);
        if ("3".equals(value)){
            throw  new LogicException("今日发送次数已用完,请明天再来");
        }
        if (value==null){
            String times = "1";
            template.opsForValue().set(key,times,1L,TimeUnit.DAYS);
        }else{
            template.opsForValue().increment(key);
        }
    }

    @Override
    public UserInfo getUserByToken(String token) {
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        if (template.hasKey(key)){
            //重新设置用户令牌在redis保存的时间
            template.expire(key,RedisKeys.USER_LOGIN_TOKEN.getTime(),TimeUnit.SECONDS);
            String userStr = template.opsForValue().get(key);
            return JSON.parseObject(userStr,UserInfo.class);
        }
        return null;
    }



}
